package com.example.socket.test;

import com.example.console.Console;
import com.example.ramcache.orm.Querier;
import com.example.socket.filter.firewall.FirewallFilter;
import com.example.socket.filter.session.SessionEvent;
import com.example.socket.filter.session.SessionListener;
import com.example.socket.filter.session.SessionManager;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan
public class App {
    public static void main(String[] args) throws Exception {
        //启动服务
        Console console = new ConsoleDefine(App.class, args);
        ApplicationContext applicationContext = console.start();
        Querier querier = applicationContext.getBean(Querier.class);
    }

    @Bean
    public SessionListener onClose() {
        return new SessionListener() {
            @Override
            public SessionEvent.Type getType() {
                return SessionEvent.Type.CLOSED;
            }

            @Override
            public void onEvent(SessionEvent event) {
                System.out.println("会话断开：" + event.getSession().getId());
            }
        };
    }

    public static class ConsoleDefine extends Console {
        private SessionManager sessionManager;
        private FirewallFilter firewallFilter;

        /**
         * 控制台构造方法
         *
         * @param applicationContext
         */
        public ConsoleDefine(Class<?> clazz, String[] args) {
            super(clazz, args);
            sessionManager = applicationContext.getBean(SessionManager.class);
            firewallFilter = applicationContext.getBean(FirewallFilter.class);
        }

        @Override
        public void stop() {
            firewallFilter.blockAll();
            sessionManager.kickAll(-1);
            super.stop();
        }
    }

}
